# coding=utf8
# 导入已存在的项目信息

import datetime

from app import create_app
from app.modules.zentao.resources import getProjectPlanInfoByUrl, initProjectPlanMembersByProjectId, db, DbCommit
from app.modules.projectPlan.models import ProjectPlanInfo

application = create_app(flask_config = 'local')


def getZenTaoPlanInfo(_obj):
    _zentao_url = _obj['url']
    _code = _obj['code']

    _rtn = getProjectPlanInfoByUrl(_zentao_url)
    if not _rtn['success']:
        print 'get zentao plan info error . %s' % _rtn['msg']
        return

    _i = _rtn['data']

    _start = datetime.datetime.strptime(_i['begin'], '%Y-%m-%d')
    _end = datetime.datetime.strptime(_i['end'], '%Y-%m-%d')

    _plan = ProjectPlanInfo.query.filter_by(zt_id = _i['id']).first()

    if _plan is not None:
        print '项目已存在  %s' % _zentao_url
        return

    if _code == '':
        _code = _i['code']

    _info = ProjectPlanInfo(plan_name = _i['name'], plan_code = _code,
                            expect_integration_date = _start, expect_release_date = _end,
                            zt_id = _i['id'], start_date = _start, end_date = _end, plan_status = 'PLAN_NEW')

    db.session.add(_info)
    DbCommit()

    initProjectPlanMembersByProjectId(_i['id'])
    print '项目添加成功  %s' % _zentao_url


def main(_obj):
    with application.app_context():
        getZenTaoPlanInfo(_obj)


if __name__ == '__main__':
    _list = [{'url': 'http://zentao.winit.com.cn/index.php?m=project&f=view&projectID=1337', 'code': ''}]
    for _obj in _list:
        main(_obj)

    pass
